package com.ruihang.generalibrary.utils;

import android.text.TextUtils;

/**
 * Created by liuyu on 2017/8/11.
 */

public class HexUtil {

    public static String encode(byte[] data){
        if (data==null){
            return null;
        }
        String ret = null;
        // 将字节数组转换为字符串
        if (data.length > 0) {
            StringBuffer sb = new StringBuffer();
            for (byte b : data) {
                //分别获取高四位和低四位转换为字符
                int h = (b >> 4) & 0x0f;
                int l = b & 0x0f;
                char ch, cl;
                if (h > 9) {//0x0a~0x0f
                    ch = (char) ('a' + (h - 10));
                } else {//0~9
                    ch = (char) ('0' + h);
                }
                if (l > 9) {//0x0a~0x0f
                    cl = (char) ('a' + (l - 10));
                } else {//0~9
                    cl = (char) ('0' + l);
                }
                sb.append(ch).append(cl);
            }
            ret = sb.toString();
        }
        return ret;
    }


    public static byte[] decode(String str){
        if (TextUtils.isEmpty(str)){
            return null;
        }
        int len = str.length();
        char[] chs = str.toCharArray();
        byte[] ret = new byte[len/2];
        int ih = 0,il=0,v=0,j=0;
        if (len > 0 && len % 2 == 0) {
            for (int i = 0; i < len - 1; i += 2,j++) {
                char ch = chs[i];
                char cl = chs[i+1];

                if(ch>='A'&&ch<='F'){
                    ih = 10 + (ch - 'A');
                }else if(ch >='a'&&ch<='f'){
                    ih = 10 + (ch - 'a');
                }else if(ch>'0'&&ch<='9'){
                    ih = ch - '0';
                }

                if(cl>='A'){
                    il = 10 + (cl - 'A');
                }else if(cl >='a'){
                    il = 10 + (cl - 'a');
                }else if(cl>'0'){
                    il = cl - '0';
                }
                v = ((ih&0x0f)<<4)|(il&0x0f);
                ret[j] = (byte)v;

            }
        }
        return ret;
    }
}
